
import SWidget from "./swidget";
import RescacheMgr from "../../framework/inc/rescachemgr";

let chkFirstCharIsHashTag = function (str) {
    if (str.charAt(0) === "#") return str.substring(1)
    return false
}

const ALIGN_LAZYFUNC = {
    "alignT": [0.5, 1],
    "alignB": [0.5, 0],
    "alignLT": [0, 1],
    "alignLB": [0, 0],
    "alignRT": [1, 1],
    "alignRB": [1, 0],
    "alignC": [0.5, 0.5],
}

export default class Image extends SWidget {
    constructor(pathokey, name) {
        name = name || "unknow_sp"
        let mt;
        let mapp;
        if (pathokey) {
            let _path = chkFirstCharIsHashTag(pathokey)
            if (_path) {
                mapp = RescacheMgr.getInstance().getTexture(_path)
                mt = new THREE.SpriteMaterial({ map: mapp });
                super(mt);
                this.scale.set(mapp.image.width, mapp.image.height, 1);
            }
            else {
                let textureLoader = new THREE.TextureLoader();
                textureLoader.load(pathokey, (mapp) => {
                    mt = new THREE.SpriteMaterial({
                        map: mapp
                    });
                    super(mt);
                    this.scale.set(mapp.image.width, mapp.image.height, 1);
                });
            }
        };
        this.name = name;

        this.lazy_init();
    }

    lazy_init() {
        let self = this;
        for (const alignstr in ALIGN_LAZYFUNC) {
            if (ALIGN_LAZYFUNC.hasOwnProperty(alignstr)) {
                const anchorarr = ALIGN_LAZYFUNC[alignstr];
                if (!self[alignstr]){
                    self[alignstr] = (function(){
                        return function(){
                            self.center = new THREE.Vector2(anchorarr[0], anchorarr[1]);
                        }
                    })();
                }
                
            }
        }
    }

    setTap(func) {
        /* 点击事件 */
        if (typeof (func) != "function") {
            console.error("setTap param typeof 'function'");
            return;
        }
        this._begainfunc = func;
        return this;
    }

    _touchend(evt) {
        if (typeof (this._begainfunc) == "function") {
            this._begainfunc();
        }
    }
}